package cc.wangzijie.ddns.aliyun.client.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

/**
 * @author wangzijie
 */
@Slf4j
public class NetworkUtil {

    private static final List<String> IP_CHECK_URLS = new ArrayList<>();
    static {
        IP_CHECK_URLS.add("wangzijie.cc:8080/ip/echo");
        IP_CHECK_URLS.add("ip.sb");
        IP_CHECK_URLS.add("ifconfig.me");
        IP_CHECK_URLS.add("icanhazip.com");
        IP_CHECK_URLS.add("ipecho.net/plain");
    }

    public static String getPublicIpAddress() {
        log.info("开始获取公网IP...");
        Map<String, Integer> resultMap = new HashMap<>(8);
        String result, maxCntResult = "";
        int count, maxCnt=0;
        for (String ipCheckUrl : IP_CHECK_URLS) {
            result = execCurl(ipCheckUrl);
            log.info("获取公网IP: 【 '{}' 】 ==> 【 '{}' 】", ipCheckUrl, result);
            if (result != null && !"".equals(result)) {
                if (resultMap.containsKey(result)) {
                    count = resultMap.get(result) + 1;
                } else {
                    count = 1;
                }
                resultMap.put(result, count);
                if (count > maxCnt) {
                    maxCnt = count;
                    maxCntResult = result;
                }
            }
        }
        StringBuilder brief = new StringBuilder();
        for(Map.Entry<String, Integer> entry : resultMap.entrySet()) {
            if (brief.length() > 0) {
                brief.append("\n");
            }
            brief.append("公网IP: 【 '").append(entry.getKey()).append("' 】: 【").append(entry.getValue()).append(" 】票");
        }
        log.info("获取公网IP结果:\n{}", brief.toString());
        return maxCntResult;
    }

    public static String execCurl(String url) {
        String[] cmds = buildCurlCmd(url);
        ProcessBuilder process = new ProcessBuilder(cmds);
        Process p;
        try {
            p = process.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
            StringBuilder builder = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
                builder.append(System.getProperty("line.separator"));
            }
            return builder.toString().trim();

        } catch (IOException e) {
            System.out.print("error");
            e.printStackTrace();
        }
        return null;
    }

    public static String[] buildCurlCmd(String url) {
        return new String[]{"curl", url, "--connect-timeout", "3"};
    }
}
